/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package acceso.util;

import static acceso.login.MenuUtil.procesarXmlMenuMovil;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.hibernate.HibernateException;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.hibernate.exception.GenericJDBCException;
import org.hibernate.exception.SQLGrammarException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import wf3.util.GeoIP;

/**
 *
 * @author Rómulo Galindo Tanta
 */
public class WorkflowUtil {

    public static final int ABRpagina = 0;
    public static final int GRApagina = 1;
    public static final String Linea = "#--------------------------------------------------------------#";
    public static final String Mensaje = "#--------------------------------------------------------------#%n[Clase: %C]%n[Fecha: %d{ISO8601}]%n[Localizacón del evento: %l]%n[Query: %m]%n %n";
    public static final String Mensaje2 = "[%c][%d{dd-MM-yyyy hh:mm:ss}][Query: %m]%n %n";
    public static final String id_frawor = "ID_FRAWOR";
    public static final String id_sesion = "session.id_sesion";
    public static final int LOG_FRAWOR = 1;
    public static final int LOG_TRANSA = 2;

    public static String quitar_html(String html) {
        try {
            html = html.replaceAll("<br>", " ");
            html = html.replaceAll("<br/>", " ");
        } catch (Exception ep) {
        }
        try {
            html = html.replaceAll("\\<.*?\\>", "");
        } catch (Exception ep) {
            System.out.println(ep.getMessage());
        }
        return html;
    }

    public static String validar_string(Object valor, String defecto) {
        String retorno = defecto;
        if (valor != null) {
            retorno = "" + valor;
        }
        return retorno;
    }

    public static long convertir_long(Object valor) {
        return convertir_entero(valor, -1);
    }

    public static long convertir_long(Object valor, long defecto) {
        long retorno = defecto;
        String valor2 = ("" + valor).trim();
        if (valor2.length() > 0) {
            try {
                retorno = Long.parseLong(valor2);
            } catch (Exception ep) {
                retorno = defecto;
            }
        } else {
            retorno = defecto;
        }
        return retorno;
    }

    public static double convertir_double(Object valor) {
        return convertir_entero(valor, -1);
    }

    public static double convertir_double(Object valor, double defecto) {
        double retorno = defecto;
        String valor2 = ("" + valor).trim();
        if (valor2.length() > 0) {
            try {
                retorno = Double.parseDouble(valor2);
            } catch (Exception ep) {
                retorno = defecto;
            }
        } else {
            retorno = defecto;
        }
        return retorno;
    }

    public static int convertir_entero(Object valor) {
        return convertir_entero(valor, -1);
    }

    public static int convertir_entero(Object valor, int defecto) {
        int retorno = defecto;

        String valor2 = ("" + valor).trim();
        if (valor2.length() > 0) {
            try {
                retorno = Integer.parseInt(valor2);
            } catch (Exception ep) {
                retorno = defecto;
            }
        } else {
            retorno = defecto;
        }
        return retorno;
    }

    public static short convertir_short(Object valor) {
        return convertir_short(valor, Short.parseShort("-1"));
    }

    public static short convertir_short(Object valor, short defecto) {
        short retorno = defecto;
        String valor2 = ("" + valor).trim();
        if (valor2.length() > 0) {
            try {
                retorno = Short.parseShort(valor2);
            } catch (Exception ep) {
                retorno = defecto;
            }
        } else {
            retorno = defecto;
        }
        return retorno;
    }

    public static Date convertir_fecha(Object valor) {
        return convertir_fecha(valor, new Date());
    }

    public static Date convertir_fecha(Object valor, Date defecto) {
        Date retorno = defecto;

        String valor2 = ("" + valor).trim();
        if (valor2.length() > 0) {
            try {
                retorno = new Date(Long.parseLong(valor2));
            } catch (Exception ep) {
                retorno = defecto;
            }
        } else {
            retorno = defecto;
        }
        return retorno;
    }

    public static boolean convertir_boolean(Object valor) {
        return convertir_boolean(valor, false);
    }

    public static boolean convertir_boolean(Object valor, boolean defecto) {
        String valor2 = ("" + valor).trim();
        if (valor2.length() > 0) {
            try {
                if (valor2.contentEquals("true") | valor2.contentEquals("1")) {
                    return true;
                } else if (valor2.contentEquals("false") | valor2.contentEquals("0")) {
                    return false;
                } else {
                    return defecto;
                }
            } catch (Exception ep) {
                return defecto;
            }
        } else {
            return defecto;
        }
    }

    public static String convertir_string(Object valor, String defecto) {
        String retorno = defecto;
        if (valor == null) {
            return retorno;
        }
        retorno = valor + "";
        if (retorno.contentEquals("undefined") | retorno.contentEquals("null")) {
            retorno = "";
        }
        return retorno;
    }

    public static String convertir_string(Object valor) {
        return convertir_string(valor, "");
    }

    public static GeoIP geoip(String IP) {
        if (IP.startsWith("192.168.") | IP.contentEquals("127.0.0.1") | IP.contentEquals("localhost")) {
            return null;
        }
        GeoIP ip = null;
        URL url;
        try {
            url = new URL("http://api.ipinfodb.com/v3/ip-city/?key=e35d0bf4bb9e667d239c781c8e896b4a2a6d5fef249f442e5721c93e3080ad22&ip=" + IP + "&format=json");
            ip = new Gson().fromJson(new BufferedReader(new InputStreamReader(url.openStream())), GeoIP.class);
        } catch (IOException | JsonSyntaxException | JsonIOException ep) {
        }
        return ip;
    }

    public static java.util.List conseguir_conpar(javax.servlet.http.HttpServletRequest request, String con) {
        java.util.List lista = new ArrayList();
        java.util.Enumeration enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String o = enu.nextElement().toString();
            if (o.startsWith(con)) {
                acceso.servlet.Conpar conpar = new acceso.servlet.Conpar();
                short id = convertir_short(o.replaceAll(con + "_", ""));
                String valor = "" + request.getParameter(o);
                conpar.setId(id);
                conpar.setValor(valor);
                lista.add(conpar);
            }
        }
        return lista;
    }

    public static java.util.List conseguir_conpar2(javax.servlet.http.HttpServletRequest request) {
        java.util.List lista = new ArrayList();
        java.util.Enumeration enu = request.getParameterNames();

        String ID_BUTTON = "";
        while (enu.hasMoreElements()) {
            String o = enu.nextElement().toString();
            if (o.startsWith("button_id_")) {
                ID_BUTTON = o.replace("button_id_", "");
                break;
            }
        }
        //System.out.println("ID_BUTTON:"+ID_BUTTON);

        if (ID_BUTTON.length() == 0) {
            return new ArrayList();
        }

        String ls_parame = request.getParameter("button_lp_" + ID_BUTTON);
        //System.out.println("ls_parame:"+ls_parame);

        if (ls_parame.length() == 0) {
            return new ArrayList();
        }

        String[] LS_PARAME = ls_parame.split(",");
        //System.out.println("LS_PARAME:"+LS_PARAME);

        for (int i = 1; i < LS_PARAME.length; i = i + 2) {
            //String no_conpar = "co_conpar_" + LS_PARAME[i];
            //v1428_1_4:5646546
            //System.out.println( "v" + request.getParameter("co_pagina") + "_1_" + LS_PARAME[i - 1]);
            String va_conpar = request.getParameter("v" + request.getParameter("co_pagina") + "_1_" + LS_PARAME[i - 1]);
            //System.out.println("va_conpar:"+va_conpar);

            acceso.servlet.Conpar conpar = new acceso.servlet.Conpar();
            conpar.setId(Short.parseShort(LS_PARAME[i]));
            conpar.setValor(va_conpar);
            lista.add(conpar);
        }
        return lista;
    }

    public static java.util.List conseguir_regist(javax.servlet.http.HttpServletRequest request, String con) {
        java.util.List lista = new ArrayList();
        java.util.Enumeration enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String o = enu.nextElement().toString();
            if (o.startsWith(con)) {
                acceso.servlet.Regist regist = new acceso.servlet.Regist();
                String[] v = o.replace(con, "").split("_");
                int id = convertir_entero(v[0]);
                short pagfil = convertir_short(v[1]);
                short pagreg = convertir_short(v[2]);
                String valor = "" + request.getParameter(o);

                regist.setPagina(id);
                regist.setPagfil(pagfil);
                regist.setPagreg(pagreg);
                regist.setValor(valor);
                lista.add(regist);
            }
        }
        return lista;
    }

    public static Document convertir_XMLString_a_DOM(String xml) {
        Document DOCUMENT;
        try {
            DocumentBuilderFactory FACTORY = DocumentBuilderFactory.newInstance();
            DocumentBuilder BUILDER = FACTORY.newDocumentBuilder();
            DOCUMENT = BUILDER.parse(new InputSource(new StringReader(xml)));
            procesarXmlMenuMovil(DOCUMENT);
        } catch (IOException | ParserConfigurationException | SAXException ex) {
            DOCUMENT = null;
        }
        return DOCUMENT;
    }

    public static String getMSGError(Exception ex) {
        String res = "";
        if (ex != null) {
            if (ex instanceof HibernateException) {
                res = ((HibernateException) ex).getMessage();
            }
            if (ex instanceof GenericJDBCException) {
                res = ((GenericJDBCException) ex).getSQLException().getMessage();
            }
            if (ex instanceof ConstraintViolationException) {
                res = ((ConstraintViolationException) ex).getSQLException().getMessage();
            }
            if (ex instanceof DataException) {
                res = ((DataException) ex).getSQLException().getMessage();
            }
            if (ex instanceof SQLGrammarException) {
                res = ((SQLGrammarException) ex).getSQLException().getMessage();
            }
            if (ex instanceof org.hibernate.exception.JDBCConnectionException) {
                res = ((org.hibernate.exception.JDBCConnectionException) ex).getSQLException().getMessage();
                if (res.indexOf("backend") > -1) {
                    res = "{El sistema esta tardando mucho en responder, por favor intentalo en unos segundos. Si este inconveniente persiste avísanos haciendo clic <a href=\"wf?co_conten=22\">aquí</a>.}";
                }
            }

            if (res.contentEquals("")) {
                res = ex.getMessage();
            }
            res = res.replace("ERROR: ", "").replace("{", "").replace("}", "");
        }
        return res;
    }

    public static boolean isMac(String agent) {
        return (agent.contains("iPad") | agent.contains("iPhone") | agent.contains("Safari")) & (!agent.contains("Chrome"));
    }
}
